const { Router } = require("../../");
const router = new Router();
const user = require("../controller/user_controller");
const emmo = require("../controller/emmo_controller");
const book = require("../controller/book_controller");
const mid01 = require("../middleware/mid01");
const mid02 = require("../middleware/mid02");

// url请求方式
router.register("get", "/user", user.index);
router.register("get", "/user/find", user.find);
router.register("post", "/user", user.add);
router.register("put", "/user/:id", user.update);
router.register("delete", "/user/:id", user.remove);

// action请求方式
router.get("book", book.index);
router.register("get", "findBook", book.find);
router.post("addBook", book.add);
router.put("updateBook", book.update);
router.delete("removeBook", book.remove);

// 其他测试
router.register("get", "/", emmo.test1);

// 中间件使用异步函数保证调用顺序执行
router.get("/2", emmo.test2, {
  middleware: [
    async (ctx, next) => {
      console.log("中间件1 执行s");
      ctx.body = "中间件1 ok";
      await next();
      console.log("中间件1 执行e");
      return { text: "中间件1" };
    },
    async (ctx, next) => {
      console.log("中间件2 执行s");
      ctx.body = "中间件2 ok";
      await next();
      console.log("中间件2 执行e");
      return { text: "中间件2" };
    },
  ],
});

router.register("post", "/3/:id/:flag", emmo.test3);

router.get("/mid", emmo.mid, { middleware: [mid01, mid02] });

router.post("/mid", emmo.mid, { middleware: [mid01, mid02] });

router.put("/mid", emmo.mid);

// cron表达式转换路由 hex编码化
const cronPath = Buffer.from("cron:0 0 * * * *", "utf-8").toString("hex");
router.put(cronPath, emmo.testTiming);

module.exports = router.routes();
